package com.hengpeng.itfinoss.controller.acm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.acl.impl.PermissionProviderImpl;
import com.hengpeng.common.acl.vo.Permission;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.AppRole;
import com.hengpeng.itfinbase.persist.PermissionPo;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.controller.vo.PermissionVo;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 角色管理控制层
 * </pre>
 * @author CHARLES
 * @version 1.0, 2010-8-10
 */
@Controller
@RequestMapping("/acm/approle")
public class AppRoleController extends BaseController
{
	@Autowired(required = false)
	protected ServiceFactory serviceFactory;

	/**
	 * <pre>
	 * 查询所有角色
	 * </pre>
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(ModelMap map, HttpServletRequest request)
	{
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			List<AppRole> result = serviceFactory.getAppUserService().findRoleWithPage(null, page.currentPage,
					page.pageSize, null);
			Long count = serviceFactory.getAppUserService().findRoleCount(null);
			page.setEntityCount(Integer.valueOf(count.toString()));
			map.put("page", page);
			map.put("appRoleList", result);
			return "acm/appRoleList";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	/**
	 * <pre>
	 * 根据ID查询角色
	 * </pre>
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/load/{id}")
	public String load(@PathVariable Long id, ModelMap map)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(id))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		try
		{
			AppRole result = serviceFactory.getPersistService().get(AppRole.class, id);
			if (result == null)
			{
				return PageHandlerUtil.returnError(map, "该角色不存在");
			}
			map.put("role", result);
			return "acm/appRoleModify";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	public static Collection<Permission> findCollectionDiff(Collection<Permission> first, Collection<Permission> second)
	{
		if (first == null || first.size() <= 0)
			return null;
		if (second == null || second.size() <= 0)
			return first;
		Collection<Permission> list = new HashSet<Permission>();
		for (Permission t : first)
		{
			boolean tr = false;
			for (Permission k : second)
			{
				if (t.getId().equals(k.getId()))
				{
					tr = true;
					break;
				}
			}
			/* 如果tr=false，即没有找到相同的元素 */
			if (!tr)
			{
				list.add(t);
			}
		}
		return list;
	}

	@RequestMapping(value = "/getStructurePermission")
	@ResponseBody
	public Map<String, ?> findStructurePermission(Long roleId)
	{
		/* 获取默认子系统 */
		String name = PermissionProviderImpl.getInstance().getDefaultSubSystem().getName();
		/* 获取系统中所有权限列表 */
		List<Permission> list = PermissionProviderImpl.getInstance().getAllPermissionBySubSystem(name);
		Map<String, Object> hashmap = new HashMap<String, Object>();
		hashmap.put("alllist", PermissionVo.clone(list));
		List<Permission> permissionAll = PermissionProviderImpl.getInstance().getAllPermissionBySubSystem(name);
		hashmap.put("rootlist", PermissionVo.clone(permissionAll));
		if (roleId != null)
		{
			// 所有权限映射表
			Map<String, PermissionVo> singleVoMap = new HashMap<String, PermissionVo>();
			List<PermissionVo> clone2 = PermissionVo.clone(permissionAll);
			for (PermissionVo p : clone2)
			{
				p.getChild().clear();
				singleVoMap.put(p.getId(), p);
			}
			AppRole result = serviceFactory.getPersistService().get(AppRole.class, roleId);
			Set<PermissionPo> listSelf = result.getPermission();
			// 创建顶级权限映射表
			Map<String, PermissionVo> relatedVoMap = new HashMap<String, PermissionVo>();
			for (PermissionPo __set : listSelf)
			{
				String id = __set.getId();
				PermissionVo permissionVo = singleVoMap.get(id);
				if (permissionVo != null)
				{
					if (permissionVo.getParentId() == null)
					{
						relatedVoMap.put(id, permissionVo);
					}
				}
			}
			// 根据角色所包含权限重建关系, 维护的对象引用和顶级权限映射表一致
			for (PermissionPo __set : listSelf)
			{
				String id = __set.getId();
				PermissionVo permission = singleVoMap.get(id);
				if (permission != null)
				{
					String parentId = permission.getParentId();
					if (parentId != null)
					{
						PermissionVo parentVo = singleVoMap.get(parentId);
						parentVo.getChild().add(permission);
					}
				}
			}
			hashmap.put("selflist", relatedVoMap.values());
		}
		return hashmap;
	}

	@RequestMapping(value = "/create")
	public String onSave(ModelMap map)
	{
		AppRole role = new AppRole();
		map.put("approle", role);
		return "acm/appRoleCreate";
	}

	@RequestMapping(value = "/save")
	public String save(String name, String description, String[] permissionIds, HttpSession session, ModelMap map)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(name))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		List<AppRole> __list = serviceFactory.getAppUserService().findUserRoles(null, name);
		if (__list.size() > 0)
		{
			return PageHandlerUtil.returnError(map, "角色名称已经存在！");
		}
		Set<PermissionPo> permissions = null;
		if (permissionIds != null && permissionIds.length > 0)
		{
			List<Permission> list = PermissionProviderImpl.getInstance().getPermission(permissionIds);
			List<PermissionPo> poList = convert(list);
			if (poList != null && poList.size() > 0)
			{
				permissions = new HashSet<PermissionPo>(poList);
			}
		}
		try
		{
			serviceFactory.getAppUserService().saveRole(name, description, permissions);
			return PageHandlerUtil.returnSuccess(map, "/acm/approle/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/modify")
	public String modify(Long id, String name, String description, String[] permissionIds, ModelMap map,
			HttpSession session)
	{
		if (PageHandlerUtil.validateObjectsNullOrEmpty(id, name))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		List<AppRole> __list = serviceFactory.getAppUserService().findUserRoles(null, name);

		if (__list.size() > 0)
		{
			if (__list.size() > 1 || !id.equals(__list.get(0).getId()))
				return PageHandlerUtil.returnError(map, "角色名称已经存在！");
		}
		Set<PermissionPo> permissions = new HashSet<PermissionPo>();
		if (permissionIds != null && permissionIds.length > 0)
		{
			List<Permission> list = PermissionProviderImpl.getInstance().getPermission(permissionIds);
			List<PermissionPo> poList = convert(list);
			if (poList != null && poList.size() > 0)
			{
				permissions = new HashSet<PermissionPo>(poList);
			}
		}
		try
		{
			serviceFactory.getAppUserService().modifyRole(id, name, description, permissions);
			return PageHandlerUtil.returnSuccess(map, "/acm/approle/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	@RequestMapping(value = "/remove")
	public String remove(Long[] ids, HttpSession session, ModelMap map)
	{
		if (PageHandlerUtil.validateArrayNullOrEmpty(ids))
		{
			return PageHandlerUtil.returnError(map, "数据没有通过验证，请刷新页面后重试！");
		}
		try
		{
			List<AppRole> list = serviceFactory.getAppUserService().findUserRoleByIds(ids);
			for (AppRole role : list)
			{
				if (role.getUsers() != null && role.getUsers().size() > 0)
				{
					return PageHandlerUtil.returnError(map, "该角色存在用户关联，不能删除！");
				}
			}
			Set<Object> set = new HashSet<Object>(Arrays.asList(ids));
			serviceFactory.getAppUserService().deleteRole(set);
			return PageHandlerUtil.returnSuccess(map, "/acm/approle/list");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return PageHandlerUtil.returnError(map, ex);
		}
	}

	private List<PermissionPo> convert(List<Permission> permissions)
	{
		List<PermissionPo> poList = new ArrayList<PermissionPo>();
		if (permissions != null)
		{
			for (Permission permission : permissions)
			{
				PermissionPo po = new PermissionPo();
				po.setId(permission.getId());
				po.setDescription(permission.getDescription());
				po.setShowText(permission.getShowText());
				poList.add(po);
			}
		}
		return poList;
	}

}
